//
//  ESVDatabase+Navigator.swift
//  ESVDatabase
//
//  Created by Vencent on 2020/11/12.
//

import Foundation
import ESVUtil
import SwifterSwift
import SwiftyUserDefaults
import RealmSwift

/// Realm专用线程

public var db: Realm? { DBManager.db }
public func dbQueue(_ block: @escaping ()->Void){
    let realmQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
    realmQueue.async {
        block()
    }
}

class DBManager {
    /// 数据库配置
    private static var configuration: Realm.Configuration {
        
        var config = Realm.Configuration(encryptionKey: getDBKey())
        
        let DBVer = UInt64(Defaults.DBVerDefaultKey)
        
        config.schemaVersion = DBVer
        
        config.fileURL = config.fileURL?.deletingLastPathComponent().appendingPathComponent("esv.realm")
        
        return config
    }
    
    /// 数据库实例
    public static var db: Realm? {
        return createDB(configuration: self.configuration)
    }
    
    /// 创建数据库
    /// - Parameters:
    ///   - number: 第几次创建
    ///   - configuration: 创建使用的Configuration
    /// - Returns: 数据库实例
    static func createDB(number: Int = 0, configuration: Realm.Configuration) -> Realm? {
        do {
            return try Realm.init(configuration: configuration)
        } catch {
            print("[DBManager] [DBManager] 创建数据库失败：", error)
            return self.repair(number: number)
        }
    }
    
    /// 数据库修复
    /// - Parameter number: 修复次数
    /// - Returns: 数据库实例
    static func repair(number: Int) -> Realm? {

        print("[DBManager] 第\(number + 1)次尝试：")
        if number < 3 {
            let ver = Int(Defaults.DBVerDefaultKey ?? 0)
            let newVer = ver + 1 + number * 5
            print("[DBManager] 自动提高数据库版本: \(ver) -> \(newVer)")
            
            Defaults.DBVerDefaultKey = newVer
            return self.createDB(number: number + 1, configuration: self.configuration)
        }else if number < 5 {
            print("[DBManager] 删除数据库重建")
            guard let fileURL = configuration.fileURL else {
                print("[DBManager] 获取数据库url失败: configuration", self.configuration)
                return nil
            }
            
            do {
                try FileManager.default.removeItem(at: fileURL)
            } catch {
                print("[DBManager] 删除数据库文件失败：fileURL: \(fileURL), error: \(error)")
            }
            
            return self.createDB(number: number + 1, configuration: self.configuration)
        }else {
            let ac = UIAlertController.init(title: "提示", message: "本次版本更新内容较多，请重新安装App后使用", preferredStyle: .alert)
            let action = UIAlertAction.init(title: "确定", style: .default, handler: nil)
            ac.addAction(action)
            UIApplication.shared.keyWindow?.rootViewController?.present(ac, animated: true, completion: nil)
            return nil
        }
    }
    
    static func getDBKey() -> Data {
        var key = keychain[data: "db"]
        
        guard let result = key else {
            // Generate a random encryption key
            var result = Data(count: 64)
            _ = result.withUnsafeMutableBytes { bytes in
                SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
            }
            key = result
            keychain[data: "db"] = key
            return result
        }
        return result
    }
}

///Extension of DefaultsKeys
public extension DefaultsKeys {
    /// 数据库版本
    var DBVer :DefaultsKey<Int> { return.init("DBVerDefaultKey", defaultValue: 0) }
}
